<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reqNo">
              <a-input v-model="model.reqNo" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId_dictText">
              <j-popup
                v-model="model.projectId_dictText"
                field="projectId"
                org-fields="id,project_name"
                dest-fields="projectId,projectId_dictText"
                code="quote_project_popup"
                :multi="false"
                @input="popupCallback"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="需求日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reqDate">
              <j-date placeholder="请选择需求日期" v-model="model.reqDate" style="width: 100%" @change="mainReqDateChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="申请类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reqType">
              <j-dict-select-tag type="list" v-model="model.reqType" dictCode="mm_purchase_reqtype" placeholder="请选择申请类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyEmpId">
              <yq-select-user-by-dep v-model="model.applyEmpId" text="realname,orgCodeTxt" :multi="false" @change="applyEmpIdChanged"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="申请日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDate">
              <j-date placeholder="请选择需求日期" v-model="model.applyDate" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="16">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" rows="2" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="申请明细" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="mmPurchaseRequisitionDetailTable.loading"
          :columns="mmPurchaseRequisitionDetailTable.columns"
          :dataSource="mmPurchaseRequisitionDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :disabledRows="mmPurchaseRequisitionDetailTable.disabledRows"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"
          :actionAddButton="false"
          @added = "detailAdded"
          @valueChange = "qtyAndPriceChange">
          <div slot="buttonBefore" class="action-button">
            <a-button slot="buttonBefore" type="primary" icon="plus" @click="chooseQuoteParts" :disabled="formDisabled">选单</a-button>
            <span class="gap"></span>
            <a-button type="primary" icon="plus" @click="chooseMaterial" :disabled="formDisabled">新增</a-button>
            <span class="gap"></span>
          </div>
        </j-editable-table>
        <j-popup-onl-report ref="jPopupOnlReport" code="mdm_popup_bom_material" multi="true" :param="materialPopupParam" @ok="addPopupCallback"/>
        <j-popup-onl-report ref="quotePartsPopReport" code="quote_parts_req_popup" multi="true" :param="quotePartsPopupParam" @ok="quotePartsPopupCallback"/>
      </a-tab-pane>
      </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import moment from "moment";
  import store from '@/store'
  import YqSelectUserByDep from '@/views/slf/components/YqSelectUserByDep'

  export default {
    name: 'MmPurchaseRequisitionForm',
    mixins: [JEditableTableModelMixin],
    components: {
      YqSelectUserByDep
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          status: '01',
          reqType: '01',
          reqDate: moment(new Date()).format('YYYY-MM-DD'),
          applyDate: moment(new Date()).format('YYYY-MM-DD'),
          applyEmpId: store.getters.userInfo.username,
          applyDeptId: store.getters.userInfo.orgCode,
        },
        quotePartsPopupParam: {},
        materialPopupParam: {},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
          reqDate: [
            { required: true, message: '请选择需求日期!'},
          ],
        },
        refKeys: ['mmPurchaseRequisitionDetail', ],
        tableKeys:['mmPurchaseRequisitionDetail', ],
        activeKey: 'mmPurchaseRequisitionDetail',
        // 采购申请明细
        mmPurchaseRequisitionDetailTable: {
          loading: false,
          dataSource: [],
          disabledRows: {},
          columns: [
            {
              title: '物料描述',
              key: 'materialDesc',
              type: FormTypes.popup,
              popupCode: 'mdm_popup_bom_material',
              orgFields: 'material_id,material_code,material_desc,material_unit_code,material_buyer_id',
              destFields: 'materialId,materialNo,materialDesc,unit,buyer',
              width:"260px",
              placeholder: '请选择${title}',
              defaultValue:'',
              jEditableParam: { jEditableInstance: null, jEditableColName: 'materialId', paramColName: 'materialIdList'},
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '单位',
              key: 'unit',
              type: FormTypes.sel_search,
              dictCode:"mdm_unit,unit_name,unit_code",
              width:"110px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '申请数量',
              key: 'reqQty',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics: true,
              scale: 2,
              validateRules: [
                { required: true, message: '${title}不能为空' },
                { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '请输入大于零的数' },
              ],
            },
            {
              title: '预估价格',
              key: 'price',
              type: FormTypes.inputNumber,
              width:"140px",
              placeholder: '请输入${title}',
              defaultValue:'',
              statistics: true,
              scale: 2
            },
            {
              title: '需求日期',
              key: 'reqDate',
              type: FormTypes.date,
              width:"160px",
              placeholder: '请输入${title}',
              defaultValue: '',
            },
            {
              title: '用途',
              key: 'uses',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '采购员',
              key: 'buyer',
              type: FormTypes.sel_user,
              multi: false,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '期望供应商',
              key: 'supplyId',
              type: FormTypes.sel_search,
              dictCode:"mdm_supply,supply_full_name,id",
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: FormTypes.input,
              width:"240px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '行号',
              key: 'lineNo',
              type: FormTypes.inputNumber,
              width:"50px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: 'materialId',
              key: 'materialId',
              type:"hidden"
            },
            {
              title: 'materialNo',
              key: 'materialNo',
              type:"hidden"
            },
            {
              title: 'status',
              key: 'status',
              type:"hidden",
              defaultValue: '01'
            },
            {
              title: 'purQty',
              key: 'purQty',
              type:"hidden",
              defaultValue: '0'
            },
            {
              title: 'quotePartsId',
              key: 'quotePartsId',
              type:"hidden",
            },
          ]
        },
        url: {
          add: "/mm/purchaseRequisition/add",
          edit: "/mm/purchaseRequisition/edit",
          queryById: "/mm/purchaseRequisition/queryById",
          genCode: "/mdm/codeRule/genCode",
          sysUserList: "/sys/user/queryUserComponentData",
          sysUserDepInfo: "/sys/user/queryDepInfoByUsername",
          mmPurchaseRequisitionDetail: {
            list: '/mm/purchaseRequisition/queryDetailListByMainId'
          },
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    methods: {
      addBefore(){
        this.genReqNo();
        this.mmPurchaseRequisitionDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      genReqNo(){
        this.confirmLoading = true
        getAction(this.url.genCode, {codeType: '14'}).then(res => {
          if (res.success) {
            this.model.reqNo = res.result;
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      editBefore(record){
        record.id = record.pid;
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { mainId: this.model.pid }
          this.requestSubTableData(this.url.mmPurchaseRequisitionDetail.list, params, this.mmPurchaseRequisitionDetailTable, this.setDisableRow)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          mmPurchaseRequisitionDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      applyEmpIdChanged(value){
        if(value){
          let that = this;
          let params = {username: value};
          getAction(this.url.sysUserDepInfo, params).then((res) => {
            if (res.success) {
              if(res.result){
                that.model['applyDeptId'] = res.result.orgCodes.split(',',1)[0];
              }
            }
          })
        }
      },
      mainReqDateChanged(value){
        let editTable = this.$refs[this.refKeys[0]];
        editTable.rows.forEach((row)=>{
          editTable.setValues([{rowKey: row.id, values:{reqDate: this.model.reqDate}}])
        });
      },
      qtyAndPriceChange(parm){
        if(parm && parm['column'] && parm['row'] && parm['target']){
          let cols = ['reqQty','price'];
          let key = parm.column.key;
          if(cols.includes(key)){
            let editableTable = parm['target'];
            // 重新计算统计列
            editableTable.recalcOneStatisticsColumn('reqQty');
            editableTable.recalcOneStatisticsColumn('price');
          }
        }
      },
      detailAdded: function (obj) {
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows;
        let num = 10;
        if(rows.length > 1){
          let lastId = editTable.getCleanId(rows[rows.length-2].id)
          let {values} = editTable.getValuesSync({ validate: false, rowIds: [lastId] });
          num = parseInt(values[0].lineNo) + 10
        }
        editTable.setValues([{rowKey: obj.row.id, values:{lineNo: num, reqDate: this.model.reqDate}}])
      },
      chooseMaterial(){
        let ids = this.getMaterialIdsChoosed()
        this.materialPopupParam = {materialIdList: ids}
        this.$refs.jPopupOnlReport.show();
      },
      addPopupCallback(rows){
        if(rows && rows.length > 0){
          let mmPurchaseRequisitionDetail = this.$refs[this.refKeys[0]];
          let oldData = mmPurchaseRequisitionDetail.getValuesSync();
          let column = this.mmPurchaseRequisitionDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = column.orgFields.split(',');
          let destFieldsArr = column.destFields.split(',');
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              mmPurchaseRequisitionDetail.add();
            }
            addRow = mmPurchaseRequisitionDetail.rows[mmPurchaseRequisitionDetail.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            mmPurchaseRequisitionDetail.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
      handleValidOk(){
        let editTable = this.$refs[this.refKeys[0]];
        let rows = editTable.rows
        if(rows.length === 0){
          this.$message.warning("请输入申请明细！");
        }else{
          this.handleOk();
        }
      },
      setDisableRow(){
        let orderDetailData = this.mmPurchaseRequisitionDetailTable.dataSource;
        if(orderDetailData.length > 0){
          let ids = orderDetailData.filter(item => item.status !== '01').map(item => item.id)
          this.mmPurchaseRequisitionDetailTable.disabledRows.id = ids
        }
      },
      popupCallback(value,row){
        this.model = Object.assign(this.model, row);
      },
      chooseQuoteParts(){
        if(!this.model.projectId){
          this.$message.error("请先选择项目！");
          return;
        }
        let ids = this.getQuotePartsIdsChoosed()
        this.quotePartsPopupParam = {quotePartsIdExcludeList: ids, projectId: this.model.projectId}
        this.$refs.quotePartsPopReport.show();
      },
      getQuotePartsIdsChoosed(){
        let editTable = this.$refs[this.refKeys[0]];
        let {values} = editTable.getValuesSync({validate: false});
        let ids = "";
        if(values && values.length > 0){
          for(let reqDetail of values){
            let quotePartsId = reqDetail.quotePartsId
            if(quotePartsId){
              ids = ids + (ids ? ',' : '') + quotePartsId
            }
          }
        }
        return ids;
      },
      getMaterialIdsChoosed(){
        let editTable = this.$refs[this.refKeys[0]];
        let {values} = editTable.getValuesSync({validate: false});
        let ids = "";
        if(values && values.length > 0){
          for(let reqDetail of values){
            if(reqDetail.materialId){
              ids = ids + (ids ? ',' : '') + reqDetail.materialId
            }
          }
        }
        return ids;
      },
      quotePartsPopupCallback(rows){
        if(rows && rows.length > 0){
          let reqDetailEditable = this.$refs[this.refKeys[0]];
          let oldData = reqDetailEditable.getValuesSync();
          let column = this.mmPurchaseRequisitionDetailTable.columns.find(col=>col.key === 'materialDesc')
          let orgFieldsArr = ['id','material_id','material_no','material_desc','unit', 'unplan_qty','unplan_price','material_buyer_id'];
          let destFieldsArr =['quotePartsId', 'materialId', 'materialNo', 'materialDesc', 'unit', 'reqQty','price','buyer'];
          let addRow, addData
          for(let i =0; i< rows.length; i++){
            if(!(i === 0 && oldData && oldData.values && oldData.values.length===1 && !oldData.values[0].materialDesc)){
              reqDetailEditable.add();
            }
            addRow = reqDetailEditable.rows[reqDetailEditable.rows.length - 1];
            // key转换
            for(let j=0; j<orgFieldsArr.length; j++){
              rows[i][destFieldsArr[j]] = rows[i][orgFieldsArr[j]];
              if(destFieldsArr[j] !== orgFieldsArr[j]){
                delete rows[i][orgFieldsArr[j]]
              }
            }
            addData = Object.assign({},rows[i])
            reqDetailEditable.popupCallback(addData.materialDesc, addData, 'materialDesc'+addRow.id, addRow, column)
          }
        }
      },
    }
  }
</script>

<style scoped>
  .action-button {
    margin-bottom: 8px;
  }
  .gap{
    margin-left: 8px;
  }
</style>